//
//  ScannerContainer.swift
//  casdon_swiftUI
//
//  Created by casdon on 2025/5/19.
//
import SwiftUI

struct ScannerContainer: View {
    @StateObject private var viewModel = ScannerContainerViewModel()
    @State private var scannedCode: String?
    @State private var isScanning = false
    @State private var showScanner = false
    
    var body: some View {
            
            ZStack{
                
                ScannerView(scannedCode: $scannedCode, isScanning: $isScanning)
                    .overlay(ScannerOverlay())
                    .edgesIgnoringSafeArea(.all)
                VStack{
                    NavigationBar(title: "添加设备", isBackBtnVisible: true, backgroundColor: Color.clear, titleColor: AppColors.White)
                    Spacer()
                    Button(action: {
                        viewModel.setTorch()
                    }) {
                        VStack{
                            Image(viewModel.isLightOn ? "light_open" : "light_close")
                                    .resizable()
                                    .scaledToFit()
                                    .frame(width: 44, height: 44)
                                
                                Text(viewModel.isLightOn ? "关闭灯光" : "打开灯光")
                                    .foregroundStyle(.white)
                                    .font(.system(size: 14))
                        }
                    }.padding(.bottom, 56)
                    
                }
                
                
            }
        
    }
}


struct ScannerOverlay: View {
    @State private var lineOffset: CGFloat = -150
    
    var body: some View {
        GeometryReader { geometry in
            let frameSize = min(geometry.size.width, geometry.size.height) * 0.7
            
            ZStack {
                Rectangle()
                    .fill(Color.black.opacity(0.4))
                    .frame(width: geometry.size.width, height: geometry.size.height)
                    .overlay(
                        RoundedRectangle(cornerRadius: 20)
                            .stroke(Color.white, lineWidth: 2)
                            .frame(width: frameSize, height: frameSize)
                    )
                    .mask(
                        RoundedRectangle(cornerRadius: 20)
                            .frame(width: frameSize, height: frameSize)
                            .blendMode(.destinationOut)
                    )
                
                Image("scanner_line")
                    .frame(width: frameSize * 0.8, height: 40)
                    .offset(y: lineOffset)
                    .onAppear {
                        withAnimation(Animation.linear(duration: 2).repeatForever(autoreverses: false)) {
                            lineOffset = 150
                        }
                    }
            }
            .compositingGroup()
        }
    }
}
